package org.apache.servicecomb.samples.practise.houserush.login.service;

import com.auth0.jwt.exceptions.TokenExpiredException;
import org.apache.http.HttpStatus;
import org.apache.servicecomb.samples.practise.houserush.login.aggregate.User;
import org.apache.servicecomb.samples.practise.houserush.login.dao.UserDao;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.stereotype.Service;

/**
 * @Author: Snake Man
 * @system:
 * @DateTime: 2022/1/2 1:41
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 注册
     * @param user
     * @return
     */
    public User createUser(User user) {
        if (userDao.findByUsername(user.getUsername()) != null) {
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST, "", "用户已经存在");
        }
        String hashedPassword = user.makeHashedPassword(user.getPassword());
        user.setHashedPassword(hashedPassword);
        return userDao.save(user);
    }

    /**
     * 查询
     * @param id
     * @return
     */
    public User findUser(int id) {
        return userDao.findOne(id);
    }

    /**
     * 删除
     * @param id
     */
    public void removeUser(int id) {
        userDao.delete(id);
    }

    /**
     * 修改密码
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    public boolean updatePassword(int id, String oldPassword, String newPassword) {
        User user = userDao.findOne(id);
        if (user == null) {
            throw new
                    InvocationException(HttpStatus.SC_BAD_REQUEST, "", "用户不存在");
        }
        if (!user.getHashedPassword().equals(user.makeHashedPassword(oldPassword))) {
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST, "", "密码错误");
        }
        user.setHashedPassword(user.makeHashedPassword(newPassword));
        userDao.save(user);
        return true;
    }

    /**
     * 登录
     * @param user
     * @return
     */
    public User signin(User user) {
        //获取用户名
        String username = user.getUsername();
        //获取密码
        String password = user.getPassword();
        //根据用户名查询用户信息
        User result = userDao.findByUsername(username);
        if (result != null && password != null) {
            if (result.getHashedPassword().equals(result.makeHashedPassword(password))) {
                //当用户登录成功，需要token进行签发
                result.generateToken();
                return result;
            }
        }
        return null;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public User verifyToken(String token) {
        int userId;
        try {
            userId = User.verifyTokenGetUserId(token);
        }catch (TokenExpiredException e){
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST,"","token过期");
        }catch (Exception e){
            throw new InvocationException(HttpStatus.SC_BAD_REQUEST,"","token解析失败");
        }
        User user = userDao.findOne(userId);
        user.generateToken();
        return user;
    }
}

